package com.study.androidsystem.anno_reflec.injectView;

import android.app.Activity;
import android.view.View;

import java.lang.reflect.Field;

/**
 * <pre>
 *     author : slx
 *     time   : 2020/12/01
 *     desc   :
 * </pre>
 */
public class InjectUtil {
    public static void inject(Activity activity) {
        Field[] declaredFields = activity.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            // 判断是否有InjectView 注解
            if (declaredField.isAnnotationPresent(InjectView.class)) {
                InjectView annotation = declaredField.getAnnotation(InjectView.class);
                int value = annotation.value();
                View viewById = activity.findViewById(value);
                declaredField.setAccessible(true);
                // 设置值
                try {
                    declaredField.set(activity,viewById);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}